import yt_dlp
import os
import re
from typing import Optional, Dict, Any

class FilterVideo:
    @staticmethod
    def detect_platform(url: str) -> Optional[str]:
        """Detect platform from URL"""
        if re.match(r'https?://(www\.)?tiktok\.com/', url):
            return 'tiktok'
        elif re.match(r'https?://(www\.)?instagram\.com/', url):
            return 'instagram'
        elif re.match(r'https?://(www\.)?(youtube\.com|youtu\.be)/', url):
            return 'youtube'
        return None

    @staticmethod
    def get_video_filename(url: str) -> Optional[str]:
        """Detect platform from URL"""
        if re.match(r'https?://(www\.)?tiktok\.com/', url):
            video_filenames = re.search(r'/video/(\d+)', url)
            video_filename = video_filenames.group(1)
            return video_filename
        elif re.match(r'https?://(www\.)?instagram\.com/', url):
            match = re.search(r'/reel/([^/?#]+)', url)
            if match:
                raw = match.group(1)
                # 替换非法文件名字符
                safe = re.sub(r'[\\/:"*?<>|]', '_', raw)
                return safe
        elif re.match(r'https?://(www\.)?(youtube\.com|youtu\.be)/', url):
            match = re.search(r"(?:v=|youtu\.be/)([A-Za-z0-9_-]{11})", url)
            if match:
                video_id = match.group(1)
                return video_id
        return None


    @staticmethod
    def progress_hook(d: Dict[str, Any]) -> None:
        if d['status'] == 'downloading':
            progress = d.get('_percent_str', 'N/A')
            speed = d.get('_speed_str', 'N/A')
            eta = d.get('_eta_str', 'N/A')
            print(f"Downloading: {progress} at {speed} ETA: {eta}", end='\r')
        elif d['status'] == 'finished':
            print("\nDownload completed, finalizing...")

    def get_ydl_options(self, platform: str, output_path: str):
        common_opts = {
            'outtmpl': output_path,
            'format': 'bestvideo+bestaudio/best',
            'merge_output_format': 'mp4',
            'noplaylist': True,
            'quiet': False,
            'progress_hooks': [self.progress_hook],
            # 'cookiesfrombrowser': ('chrome',),  # Uncomment if needed
            'http_headers': {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
                'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
            }
        }

        if platform == 'tiktok':
            common_opts['extractor_args'] = {'tiktok': {'webpage_download': True}}
            common_opts['http_headers'].update({
                'Referer': 'https://www.tiktok.com/',
                'Origin': 'https://www.tiktok.com',
            })

        elif platform == 'instagram':
            common_opts['http_headers'].update({
                'Referer': 'https://www.instagram.com/',
                'Origin': 'https://www.instagram.com',
            })

        elif platform == 'youtube':
            common_opts['http_headers'].update({
                'Referer': 'https://www.youtube.com/',
                'Origin': 'https://www.youtube.com',
            })

        return common_opts